package com.ruitaowang.admin.view.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruitaowang.core.domain.*;
import com.ruitaowang.goods.service.*;
import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.RoleService;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.account.service.WalletService;
import com.ruitaowang.core.properties.ConfigProperties;
import com.ruitaowang.core.utils.JwdUtils;
import com.ruitaowang.core.utils.QRCode;
import com.ruitaowang.core.utils.TimeUtils;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.dao.Base64ImgMapper;

import wx.wechat.common.Configure;

/**
 * Created by Shaka on 2017/1/4.
 */
@RestController
public class APICompanyController extends BaseController {
    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
    @Autowired
    private CompanyService companyService;
    @Autowired
    private CompanyProductService companyProductService;
    @Autowired
    private WalletCompanyService walletCompanyService;
    @Autowired
    private Base64ImgMapper base64ImgMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ConfigProperties configProperties;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ExPriceService exPriceService;
    @Autowired
    private LogisticsService logisticsService;
    @Autowired
    private UserOnlineService userOnlineService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private UserHistoricalTraceService userHistoricalTraceService;
    @Autowired
    private UserMembersService userMembersService;
    @Autowired
    private DistrictService districtService;
    @Autowired
    private CompanyTypeService companyTypeService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private HistoricalRecordService historicalRecordService;
    @Autowired
    private GoodsSearchService goodsSearchService;
    @Autowired
    private CompanyIndustryService companyIndustryService;
    @Autowired
    private QRCodeRecordService qrCodeRecordService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private LsMsgService lsMsgService;
    @Autowired
    private UserProfitService userProfitService;

    private void init() {
        //init
        Configure.hostAPI = configProperties.getHostAPI();
        Configure.hostOSS = configProperties.getHostOSS();
        Configure.hostWap = configProperties.getHostWap();
        Configure.returnUri = configProperties.getReturnUri();
        Configure.wxpay_notify_url = configProperties.getHostAPI() + "/api/wxs/notify";
    }

//    /**
//     * 商家聯盟 商家下分裂三个商品
//     * (必须现金类商品 goodsPayType=0)
//     *
//     * @param company
//     * @param page
//     * @return
//     */
//    @RequestMapping("/api/company")
//    public String list(Company company, int page) {
//        company.setPage(page);
//        if (!ObjectUtils.isEmpty(company.getSidx())) {
//            company.setOrderBy(company.getSidx() + " " + company.getSord() + "," + company.getOrderBy());
//        }
//        HashSet<Long> setgoodId = new HashSet<>();
//        List<Company> companies = companyService.selectForPage(company);
//        for (Company where : companies) {
//            setgoodId.add(where.getCompanyId());
//        }
//        List<CompanyVO> mainCompany = new ArrayList<>();
//        CompanyVO companyVO = null;
//        Goods goods = new Goods();
//        for (Long thisId : setgoodId) {
//            Company company1 = companyService.selectByPK(thisId);
//            companyVO = new CompanyVO();
//            BeanUtils.copyProperties(company1, companyVO);
//            goods.setPage(1);
//            goods.setRows(3);
//            goods.setRstatus((byte) 0);
//            goods.setGoodsPayType((byte) 0);
//            goods.setGoodsOnline((byte) 1);
//            goods.setGoodsProviderId(companyVO.getCompanyId());
//            List<GoodsVO> goodsVOS=goodsService.selectForPage(goods);
//            companyVO.setGoodsList();
//            mainCompany.add(companyVO);
//        }
//        MsgOut o = MsgOut.success(mainCompany);
//        o.setRecords(company.getRecords());
//        o.setTotal(company.getTotal());
//        return this.renderJson(o);
//    }

    @RequestMapping(value = "/api/admin/company/selectByPk/{id}")
    public String selectByPk(@PathVariable("id") long id) {
        MsgOut msgOut = MsgOut.success(companyService.selectByPK(id));
        return renderJson(msgOut);
    }

    @RequestMapping(value = "/api/wap/company/SelectOnly/{id}")
    public String wapSelectOnly(@PathVariable("id") long id) {
        Company company = companyService.selectByPK(id);
        CompanyVO companyVO = new CompanyVO();
        BeanUtils.copyProperties(company, companyVO);
        Long industryId = companyIndustryService.selectByPK(companyTypeService.selectByPK(company.getCompanyTypeId()).getIndustryId()).getId();
        if(industryId == 45){
            companyVO.setIskefu(1);
        } else {
            companyVO.setIskefu(0);
        }
        MsgOut msgOut = MsgOut.success(companyVO);
        return renderJson(msgOut);
    }

    @RequestMapping(value = "/api/wap/company/community/{companyId}")
    public String community(@PathVariable("companyId") long companyId, @RequestHeader(value = "headId", required = false) Long userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Company company = companyService.selectByPK(companyId);
        CompanyVO companyVO = new CompanyVO();
        BeanUtils.copyProperties(company, companyVO);
        //高级合伙人加上商家权限
        if(company.getPayCommunity() != 1){
            QRCodeRecord qrCodeRecord = new QRCodeRecord();
            qrCodeRecord.setUserId(company.getUserId());
            List<QRCodeRecord> qrCodeRecordList = qrCodeRecordService.select(qrCodeRecord);
            if (!ObjectUtils.isEmpty(qrCodeRecordList)) {
                if(qrCodeRecordList.get(0).getBuyStatus() == 2){
                    companyVO.setPayCommunity((byte)1);
                }
            }
        }
        if(userId.equals(company.getUserId())){
            companyVO.setIsme(1);
        } else {
            companyVO.setIsme(0);
        }
        MsgOut msgOut = MsgOut.success(companyVO);
        return renderJson(msgOut);
    }

    @RequestMapping(value = "/api/wap/company/update", method = RequestMethod.PUT)
    public String wapUpdateCompany(Company company, @RequestHeader(value = "headId", required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        String[] imgHeadPhotoList = company.getImgHeadPhoto().split(",");
        if(imgHeadPhotoList.length > 4){
            return this.renderJson(MsgOut.error("Upload 4 pictures at most."));
        }
        companyService.updateNew(company);
        MsgOut o = MsgOut.success(company);
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/admin/company/phone 后台管理-商家管理-商家入住-电话验证
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/company/phone
     * @apiName adminCompanyPhone
     * @apiGroup Company
     * @apiParam {int} phone SysUser电话.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "address": "北京市东城区 远洋商务",
     * "auditCause": "",
     * "bankAccount": "0",
     * "bankDeposit": "0",
     * "bankId": "11",
     * "bankName": "0",
     * "businessLicenseNumber": "1",
     * "city": "东城区",
     * "coPayType": 3,
     * "coType": 0,
     * "companyGoodsCategotyId": 0,
     * "companyId": 111,
     * "companyName": "春亭的小店",
     * "companyStatus": 1,
     * "companyType": 1,
     * "ctime": 1491882741056,
     * "district": "",
     * "districtId": 1,
     * "headimgurl": "http://wx.qlogo.cn/mmopen/Aqtvh6YDJ6SP5dMJAIiahP4HDIcCrb07agWgA8Nbrs8iaTbLQ7KT55Ocw906ftK2ldKiaLd8ZI1uYJVqxVpp9qibXqTCpibpgWPia6/0",
     * "imgBusinessLicense": "",
     * "imgIdBack": "92",
     * "imgIdFront": "91",
     * "imgOrganizationCodeCertificate": "",
     * "imgTaxRegistrationCertificate": "",
     * "jmId": "230811199502250031",
     * "linkman": "信春廷",
     * "mobile": "15910288070",
     * "mtime": 1492502101017,
     * "pid": 0,
     * "province": "北京市",
     * "rangeSort": 0,
     * "redirectType": 0,
     * "remark": "服装",
     * "rstatus": 0,
     * "userId": 18233,
     * "xlErCert": ""
     * }
     * ],
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/admin/company/phone"
     * }
     */
    @RequestMapping("/api/admin/company/phone")
    public String adminCompanyPhone(SysUser sysUser) {
        Map map = new HashMap();
        List<SysUser> list = sysUserService.select(sysUser);
        if (ObjectUtils.isEmpty(list)) {
            return this.renderJson(MsgOut.error("查询不到用户信息，请先注册龙蛙"));
        }
        Company company = new Company();
        company.setUserId(list.get(0).getId());
        List<Company> companies = companyService.select(company);
        map.put("companies", companies);
        map.put("sysUser", list.get(0).getId());
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/admin/company 后台管理-商家管理-商家列表
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/company
     * @apiName findCompanyPage
     * @apiGroup Company
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "address": "江苏省镇江市丹阳市 高新技术创新园（南三环中兴路路口）",
     * "auditCause": "",
     * "bankAccount": "0",
     * "bankDeposit": "0",
     * "bankId": "",
     * "bankName": "0",
     * "businessLicenseNumber": "",
     * "city": "镇江市",
     * "coPayType": 3,
     * "coType": 0,
     * "companyGoodsCategotyId": 22,
     * "companyId": 275,
     * "companyName": "中视光学眼镜丹阳公司",
     * "companyStatus": 1,
     * "companyType": 8,
     * "ctime": 1500866747519,
     * "district": "丹阳市",
     * "districtId": 1303,
     * "headimgurl": "",
     * "imgBusinessLicense": "",
     * "imgIdBack": "http://static.ruitaowang.com/attached/file/20170724/20170724112006_64.jpg",
     * "imgIdFront": "http://static.ruitaowang.com/attached/file/20170724/20170724111939_12.jpg",
     * "imgOrganizationCodeCertificate": "http://static.ruitaowang.com/attached/file/20170724/20170724112047_387.jpg",
     * "imgTaxRegistrationCertificate": "",
     * "jmId": "321102196507292817",
     * "linkman": "梁鹤平",
     * "mobile": "15952915379",
     * "mtime": 1500879970181,
     * "province": "江苏省",
     * "rangeSort": 0,
     * "remark": "",
     * "rstatus": 0,
     * "userId": 6249,
     * "xlErCert": ""
     * }
     * ],
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/admin/company"
     * }
     */
    @RequestMapping("/api/admin/company")
    public String findCompanyPage(Company company, int page) {
        company.setPage(page);
        if (!ObjectUtils.isEmpty(company.getSidx())) {
            company.setOrderBy(company.getSidx() + " " + company.getSord() + "," + company.getOrderBy());
        }
        CompanyType companyType = new CompanyType();
        companyType.setIndustryId(company.getCompanyId());
        company.setCompanyId(null);
        List<Company> companies = companyService.selectSearchForPage(company);
        List<Company> companyList = new ArrayList<>();
        MsgOut o = null;
        if (companyType.getIndustryId() == null && company.getCompanyTypeId() == null) {
            companyList = companies;
        } else if (companyType.getIndustryId() != null && company.getCompanyTypeId() == null) {
            //只传行业不传商家类型的情况
            List<CompanyType> companyTypes = companyTypeService.select(companyType);
            if (companies == null || companyTypes == null) {
                LOGGER.info("companies为空！或companyTypes为空！");
                companyList = companies;
            } else {
                int count = companies.size();
                int typeCount = companyTypes.size();
                for (int i = 0; i < count; i++) {

                    if (companies.get(i) == null) {
                        break;
                    }
                    if (companies.get(i).getCompanyTypeId() == null) {
                        continue;
                    }
                    long companyTypeId = companies.get(i).getCompanyTypeId();
                    for (int j = 0; j < typeCount; j++) {
                        long typeId = companyTypes.get(j).getId();
                        if (companyTypeId == typeId) {
                            companyList.add(companies.get(i));
                            break;
                        }
                    }
                }

            }
        } else {
            companyList = companies;
        }

//        if (!ObjectUtils.isEmpty(companies)) {
//            for (Company c:companies) {
//                if (c.get.getCompanyType() == 12 && companies.get(i).getPid() != 0) {
//                    companies.get(i).setAddress(districtName(companies.get(i).getPid()));
//                }
//            }
//        }
        o = MsgOut.success(companyList);
        o.setRecords(company.getRecords());
        o.setTotal(company.getTotal());
        return this.renderJson(o);
    }

    @RequestMapping("/api/admin/companyByCZ")
    public String selectByCZ(Company company, int page) {
        company.setPage(page);
        List<Company> companyList = companyService.selectByCZ(company);
        MsgOut o = MsgOut.success(companyList);
        o.setRecords(company.getRecords());
        o.setTotal(company.getTotal());
        return this.renderJson(o);
    }



    /**
     * @api {put} /api/admin/company 后台管理-商家管理-商家列表-详情修改
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/company
     * @apiName updateCompany
     * @apiGroup Company
     * @apiParam {int} companyId 商户ID.
     * @apiParam {int} companyType 商户类型.
     * @apiParam {string} companyName 商户名称.
     * @apiParam {int} userId 归属人ID.
     * @apiParam {int} linkman 负责人姓名.
     * @apiParam {int} mobile 商户电话.
     * @apiParam {int} jmId  法人身份证号码.
     * @apiParam {int} businessLicenseNumber 商业许可证.
     * @apiParam {string} headimgurl 公司logo.
     * @apiParam {string} imgBusinessLicense 工商营业执照.
     * @apiParam {string} imgIdFront 身份证（正面）.
     * @apiParam {string} imgIdBack 身份证（反面）.
     * @apiParam {string} imgOrganizationCodeCertificate 组织机构代码证.
     * @apiParam {string} xlErCert 心理咨询二级证.
     * @apiParam {int} bankAccount  银行卡开户人.
     * @apiParam {int} bankName  银行卡开户行.
     * @apiParam {string} bankId  银行卡账号.
     * @apiParam {string} address  详细地址.
     * @apiParam {int} redirectType  跳转至商户店铺,跳转至龙蛙商城首页.
     * @apiParam {int} auditCause  审核原因.
     * @apiParam {int} remark  备注信息.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "address": "湖北省黄冈市蕲春县 李时珍国际医药港",
     * "auditCause": "",
     * "bankAccount": "0",
     * "bankId": "",
     * "bankName": "0",
     * "businessLicenseNumber": "",
     * "companyId": 276,
     * "companyName": "艾大姐",
     * "companyType": 1,
     * "jmId": "421126197807011756",
     * "linkman": "童志勇",
     * "mobile": "13986541122",
     * "mtime": 1504512258489,
     * "redirectType": 0,
     * "remark": "蕲艾",
     * "userId": 5624
     * }
     * ],
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/admin/company"
     * }
     */
    @RequestMapping(value = "/api/admin/company", method = RequestMethod.PUT)
    public String updateCompany(Company company) {
        companyService.update(company);
        //审核通过，送高级合伙人
//        if(company.getCompanyStatus() == 1){
//            QRCodeRecord qrCodeRecord = new QRCodeRecord();
//            qrCodeRecord.setUserId(company.getUserId());
//            List<QRCodeRecord> qrCodeRecordList = qrCodeRecordService.select(qrCodeRecord);
//            qrCodeRecord.setBuyStatus((byte)2);
//            if (ObjectUtils.isEmpty(qrCodeRecordList)) {
//                qrCodeRecordService.insert(qrCodeRecord);
//            }else{
//                qrCodeRecord.setId(qrCodeRecordList.get(0).getId());
//                qrCodeRecordService.update(qrCodeRecord);
//            }
//        }
        MsgOut o = MsgOut.success(company);
        return this.renderJson(o);
    }

    @RequestMapping("/api/admin/company/audit")
    public String updateaudit(Company company) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Company where = new Company();
        where.setCompanyId(company.getCompanyId());
        where.setCompanyStatus(company.getCompanyStatus());
        where.setCompanyType(company.getCompanyType());
        where.setAuditCause(company.getAuditCause());
        where = companyService.update(where);
        MsgOut o = MsgOut.success(where);
        Company c = companyService.selectByPK(company.getCompanyId());
        if (ObjectUtils.isEmpty(c)) {
            return this.renderJson(MsgOut.error("参数错误"));
        }
        //区域代理商入住  审核
        if (company.getCompanyStatus() == 1 && c.getCompanyType() == 12 && c.getPid() != 0) {
            //地区归属人修改
            District district = districtService.selectByPK(c.getPid());
            district.setCityUserId(c.getUserId());
            district.setInitial(TimeUtils.getNextYearCurrentDate());
            districtService.update(district);
            //会员增加会员角色
            UserMembers userMembers = new UserMembers();
            userMembers.setUserId(c.getUserId());
            userMembers.setMemberType((byte) 7);
            List<UserMembers> userMembersList = userMembersService.select(userMembers);
            if (ObjectUtils.isEmpty(userMembersList)) {
                userMembers.setStartTime(TimeUtils.getCurrentDate());
                userMembers.setEndTime(TimeUtils.getNextYearCurrentDate());
                userMembersService.insert(userMembers);
            }
        }
//        //区域代理商入住  审核未通过
//        if (company.getCompanyStatus() == 0 && c.getCompanyType() == 12 && c.getPid() != 0) {
//            //地区归属人修改
//            District district = districtService.selectByPK(c.getPid());
//            district.setCityUserId(c.getUserId());
//            district.setInitial(TimeUtils.getNextYearCurrentDate());
//            districtService.update(district);
//            //会员增加会员角色
//            UserMembers userMembers = new UserMembers();
//            userMembers.setUserId(c.getUserId());
//            userMembers.setMemberType((byte) 6);
//            List<UserMembers> userMembersList = userMembersService.select(userMembers);
//            if (ObjectUtils.isEmpty(userMembersList)) {
//                userMembers.setStartTime(TimeUtils.getCurrentDate());
//                userMembers.setEndTime(TimeUtils.getNextYearCurrentDate());
//                userMembersService.insert(userMembers);
//            }
//        }
        //云动店审核  增加会员角色身份
        if (company.getCompanyStatus() == 1 && c.getCompanyType() == 11 || company.getCompanyStatus() == 1 && c.getCompanyType() == 13) {
            UserMembers userMembers = new UserMembers();
            userMembers.setUserId(company.getUserId());
            userMembers.setMemberType((byte) 9);
            List<UserMembers> userMembersList = userMembersService.select(userMembers);
            if (ObjectUtils.isEmpty(userMembersList)) {
                userMembers.setStartTime(TimeUtils.getCurrentDate());
                userMembers.setEndTime(TimeUtils.getNextYearCurrentDate());
                userMembersService.insert(userMembers);
            }
        }
//        roleId
//        7	供货商	 	编辑删除
//        6	微商	个人开店	编辑删除
//        5	扫码签到	教育培训	编辑删除
//        4	实体店铺	个人中心->个人信息，本地订单，创建二维码，二维码列表	编辑删除
//        3	普通会员	个人中心->个人信息	编辑删除
//        2	系统管理员	权限管理	编辑删除
//        1	物料管理员


//        商家类型 companyType
//        0 实体店
//        1 微商
//        2 心理咨询
//        3 城市合伙人
//        4 梦想合伙人
//        5 教育培训
//        6 联合创始人
//        7 艺术家
//        8 供货商

        if (company.getCompanyStatus() == 1) {
            //grant
            Long userId = where.getUserId();
            if (userId.intValue() != 11) {
                if (where.getCompanyType() == 0) {
                    roleService.grantUserRoleForAppend(userId, "4");
                } else if (where.getCompanyType() == 1) {
                    roleService.grantUserRoleForAppend(userId, "6");
                } else if (where.getCompanyType() == 2) {
                    roleService.grantUserRoleForAppend(userId, "4");
                } else if (where.getCompanyType() == 3) {
                    roleService.grantUserRoleForAppend(userId, "4");
                } else if (where.getCompanyType() == 4) {
                    roleService.grantUserRoleForAppend(userId, "4");
                } else if (where.getCompanyType() == 5) {
                    roleService.grantUserRoleForAppend(userId, "4");
                } else if (where.getCompanyType() == 6) {
                    roleService.grantUserRoleForAppend(userId, "4");
                } else if (where.getCompanyType() == 7) {
                    roleService.grantUserRoleForAppend(userId, "4");
                } else if (where.getCompanyType() == 8) {
                    roleService.grantUserRoleForAppend(userId, "7");
                }
            }
        }
        return this.renderJson(o);
    }

    /**
     * @api {post} /api/admin/company/cellEdit 后台管理-商家管理-商家列表-[审核状态CellEdit]
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/company/cellEdit
     * @apiPermission admin
     * @apiName updateCompanyForCellEdit
     * @apiGroup Company
     * @apiParam {int} id 订单ID[必选].
     * @apiParam {int} auditStatus 审核状态[必选].
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "auditStatus": 2,
     * "id": 363,
     * }
     * ],
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/admin/company/cellEdit"
     * }
     */
    @RequestMapping(value = "/api/admin/company/cellEdit", method = RequestMethod.POST)
    public String updateCompanyForCellEdit(Company company, Long id) {
        company.setCompanyId(id);
        companyService.update(company);
        MsgOut o = MsgOut.success(company);
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/admin/company/goodsProviders 后台管理-订单-查询供货商
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/company/goodsProviders
     * @apiName findGoodsProvider
     * @apiGroup Company
     * @apiParam {int} goodsId 商品ID[必选].
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "address": "北京市朝阳区四惠远洋商务1406",
     * "auditCause": "0",
     * "bankAccount": "0",
     * "bankDeposit": "0",
     * "bankId": "",
     * "bankName": "0",
     * "businessLicenseNumber": "",
     * "city": "",
     * "coPayType": 0,
     * "coType": 0,
     * "companyGoodsCategotyId": 0,
     * "companyId": 1,
     * "companyName": "龙蛙天乐",
     * "companyStatus": 1,
     * "companyType": 127,
     * "ctime": 1484202120549,
     * "district": "",
     * "districtId": 0,
     * "headimgurl": "http://www.ruitaowang.com/favicon.jpg",
     * "imgBusinessLicense": "",
     * "imgIdBack": "",
     * "imgIdFront": "",
     * "imgOrganizationCodeCertificate": "",
     * "imgTaxRegistrationCertificate": "",
     * "jmId": "130423199305264311",
     * "linkman": "王总",
     * "mobile": "18310882968",
     * "mtime": 1484202120549,
     * "pid": 0,
     * "province": "",
     * "rangeSort": 0,
     * "redirectType": 0,
     * "remark": "",
     * "rstatus": 0,
     * "userId": 0,
     * "xlErCert": ""
     * }
     * ],
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/admin/company/goodsProviders"
     * }
     */
    @RequestMapping(value = "/api/admin/company/goodsProviders", method = RequestMethod.GET)
    public String findGoodsProvider(Long goodsId) {
        Goods goods = goodsService.selectByPK(goodsId);
        Company company = companyService.selectByPK(goods.getGoodsProviderId());
        MsgOut o = MsgOut.success(company);
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/admin/company/providers 后台管理-商家管理-过滤的商家列表
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/company/providers
     * @apiName findCompanyForProvider
     * @apiGroup Company
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "address": "北京市朝阳区四惠远洋商务1406",
     * "auditCause": "0",
     * "bankAccount": "0",
     * "bankDeposit": "0",
     * "bankId": "",
     * "bankName": "0",
     * "businessLicenseNumber": "",
     * "city": "",
     * "coPayType": 0,
     * "coType": 0,
     * "companyGoodsCategotyId": 0,
     * "companyId": 1,
     * "companyName": "龙蛙天乐",
     * "companyStatus": 1,
     * "companyType": 127,
     * "ctime": 1484202120549,
     * "district": "",
     * "districtId": 0,
     * "headimgurl": "http://www.ruitaowang.com/favicon.jpg",
     * "imgBusinessLicense": "",
     * "imgIdBack": "",
     * "imgIdFront": "",
     * "imgOrganizationCodeCertificate": "",
     * "imgTaxRegistrationCertificate": "",
     * "jmId": "130423199305264311",
     * "linkman": "王总",
     * "mobile": "18310882968",
     * "mtime": 1484202120549,
     * "pid": 0,
     * "province": "",
     * "rangeSort": 0,
     * "redirectType": 0,
     * "remark": "",
     * "rstatus": 0,
     * "userId": 0,
     * "xlErCert": ""
     * }
     * ],
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/admin/company/providers"
     * }
     */
    @RequestMapping("/api/admin/company/providers")
    public String findCompanyForProvider(Company company) {
        List<Company> companyList = companyService.select(company);
        List<Company> companies = new ArrayList<>();
        //梁品铺子
        Company company1 = companyService.selectByPK((long)281);
        //仁和旗舰店
        Company company2 = companyService.selectByPK((long)346);
        if (ObjectUtils.isEmpty(companyList)) {
            return this.renderJson(MsgOut.success("nodata"));
        }
        if (!ObjectUtils.isEmpty(company1)) {
            companies.add(company1);
        }
        if (!ObjectUtils.isEmpty(company2)) {
            companies.add(company2);
        }
        companyList.forEach(com -> {
            if ((com.getCompanyType() == 0 || com.getCompanyType() == 1 || com.getCompanyType() == 7 || com.getCompanyType() == 8 || com.getCompanyType() == 11 || com.getCompanyType() == 127)
                    && com.getCompanyId() != 281 && com.getCompanyId() != 346) {
                companies.add(com);
            }
        });
        MsgOut o = MsgOut.success(companies);
        return this.renderJson(o);
    }

    /**
     * ws获取供应商
     *
     * @param company
     * @return
     */
    @RequestMapping(value = "/api/providers")
    public String providers(Company company) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        company.setUserId(user.getId());
        List<Company> companyList = companyService.select(company);
        List<Company> companies = new ArrayList<>();
        if (ObjectUtils.isEmpty(companyList)) {
            return this.renderJson(MsgOut.success("nodata"));
        }
        companyList.forEach(com -> {
            if (com.getCompanyType() == 0 || com.getCompanyType() == 1 || com.getCompanyType() == 7 || com.getCompanyType() == 8 || com.getCompanyType() == 11 || com.getCompanyType() == 127) {
                companies.add(com);
            }
        });
        if (!ObjectUtils.isEmpty(companies)) {
            MsgOut o = MsgOut.success(companies);
            return this.renderJson(o);
        } else {
            return this.renderJson(MsgOut.error("您还不是商家用户"));
        }
    }

    @RequestMapping(value = "/api/isPay", method = RequestMethod.GET)
    public String isPay(Order order, @RequestHeader(value = "headId", required = false) String userId){
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        order.setPayStatus((byte)1);
        order.setUserId(Long.parseLong(userId));
        order.setRemark("1832");
        List<Order> orders=orderService.select(order);
        if (ObjectUtils.isEmpty(orders)){
            MsgOut o = MsgOut.success("未支付");
            o.setCode(4);
            return this.renderJson(o);
        }else {
            MsgOut o = MsgOut.success("已支付");
            o.setCode(5);
            return this.renderJson(o);
        }
    }


    @RequestMapping(value = "/api/company", method = RequestMethod.POST)
    public String create(Company company, @RequestHeader(value = "headId", required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (company.getStoreClassification() == 2 && company.getDepositStatus() == 0){
            Order order  = new Order();
            order.setPayStatus((byte)1);
            order.setUserId(Long.parseLong(userId));
            order.setRemark("1832");
            List<Order> orders=orderService.select(order);
            if (ObjectUtils.isEmpty(orders)){
                return this.renderJson("请交纳店铺押金");
            }else {
                company.setDepositStatus((byte)1);
            }
        }
        SysUser user = sysUserService.selectByPK(Long.parseLong(userId));
        // '0： 普通会员 （消费者 两类1 网站消费，2 实体店扫码消费，没有绑定手机号）\n1：本地生活 商家用户\n2：城市合伙人\n4：区代理 ',
        Company tmp = new Company();
        tmp.setUserId(user.getId());
        List<Company> resList = companyService.select(tmp);
        if (resList != null && resList.size() > 0) {
            return this.renderJson("不能重复加入");
        }
        company.setUserId(user.getId());
        company.setCompanyType((byte) 1);
        companyService.insert(company);
        MsgOut o = MsgOut.success(company);
        return this.renderJson(o);
    }

    /**
     * 商家入驻
     *
     * @param company
     * @param companyProduct
     * @return
     */
    @RequestMapping(value = "/api/companyAll", method = RequestMethod.POST)
    public String createAll(Company company, CompanyProduct companyProduct) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        init();
        // '0： 普通会员 （消费者 两类1 网站消费，2 实体店扫码消费，没有绑定手机号）\n1：本地生活 商家用户\n2：城市合伙人\n4：区代理 ',
        Company before = companyService.selectByUserIdAndCompanyType(user.getId(), company.getCompanyType());
        if (!ObjectUtils.isEmpty(before)) {
            return this.renderJson(MsgOut.error("您已提交过申请，请耐心等待。"));
        }
        if (ObjectUtils.isEmpty(company.getMobile())) {
            return this.renderJson(MsgOut.error("信息录入不完全"));
        }
        company.setUserId(user.getId());
        company.setCompanyType((byte) 1);
        Company newCompany = companyService.insert(company);

        companyProduct.setCompanyId(newCompany.getCompanyId());
        companyProduct = companyProductService.insert(companyProduct);
        companyProduct.setQrcodeUrl(QRCode.rulesQRForSMPay(System.getProperty("catalina.base"), user.getId(), companyProduct.getProductId()));
        companyProductService.update(companyProduct);
        MsgOut o = MsgOut.success(company);
        return this.renderJson(o);
    }

    /**
     * @api {post} /api/admin/company 后台管理-商家管理-商家入住
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/company
     * @apiPermission admin
     * @apiName updateCompany
     * @apiGroup Company
     * @apiParam {int} companyId 商户ID.
     * @apiParam {int} companyType 商户类型.
     * @apiParam {string} companyName 商户名称.
     * @apiParam {int} userId 归属人ID.
     * @apiParam {int} linkman 负责人姓名.
     * @apiParam {int} mobile 商户电话.
     * @apiParam {int} jmId  法人身份证号码.
     * @apiParam {int} businessLicenseNumber 商业许可证.
     * @apiParam {string} headimgurl 公司logo.
     * @apiParam {string} imgBusinessLicense 工商营业执照.
     * @apiParam {string} imgIdFront 身份证（正面）.
     * @apiParam {string} imgIdBack 身份证（反面）.
     * @apiParam {string} imgOrganizationCodeCertificate 组织机构代码证.
     * @apiParam {string} xlErCert 心理咨询二级证.
     * @apiParam {int} bankAccount  银行卡开户人.
     * @apiParam {int} bankName  银行卡开户行.
     * @apiParam {string} bankId  银行卡账号.
     * @apiParam {string} address  详细地址.
     * @apiParam {int} redirectType  跳转至商户店铺,跳转至龙蛙商城首页.
     * @apiParam {int} auditCause  审核原因.
     * @apiParam {int} remark  备注信息.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "address": "北京市朝阳区四惠远洋商务1406",
     * "auditCause": "0",
     * "bankAccount": "0",
     * "bankDeposit": "0",
     * "bankId": "",
     * "bankName": "0",
     * "businessLicenseNumber": "",
     * "city": "",
     * "coPayType": 0,
     * "coType": 0,
     * "companyGoodsCategotyId": 0,
     * "companyId": 1,
     * "companyName": "龙蛙天乐",
     * "companyStatus": 1,
     * "companyType": 127,
     * "ctime": 1484202120549,
     * "district": "",
     * "districtId": 0,
     * "headimgurl": "http://www.ruitaowang.com/favicon.jpg",
     * "imgBusinessLicense": "",
     * "imgIdBack": "",
     * "imgIdFront": "",
     * "imgOrganizationCodeCertificate": "",
     * "imgTaxRegistrationCertificate": "",
     * "jmId": "130423199305264311",
     * "linkman": "王总",
     * "mobile": "18310882968",
     * "mtime": 1484202120549,
     * "pid": 0,
     * "province": "",
     * "rangeSort": 0,
     * "redirectType": 0,
     * "remark": "",
     * "rstatus": 0,
     * "userId": 0,
     * "xlErCert": ""
     * }
     * ],
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/admin/company"
     * }
     */
    @RequestMapping(value = "/api/admin/company", method = RequestMethod.POST)
    public String adminCreate(Company company, CompanyProduct companyProduct, String userPhone) {
        SysUser sysUser = new SysUser();
        sysUser.setPhone(userPhone);
        List<SysUser> list = sysUserService.select(sysUser);
        if (ObjectUtils.isEmpty(list)) {
            return this.renderJson(MsgOut.error("归属用户用户没有注册，请先注册"));
        } else {
            company.setUserId(list.get(0).getId());
        }
        Company myCompany = companyService.selectByUserId(company.getUserId());
        if (!ObjectUtils.isEmpty(myCompany)) {
            return this.renderJson(MsgOut.error("该用户已经有商户 勿重复注册"));
        }
        Company newCompany = companyService.insert(company);
        companyProduct.setCompanyId(newCompany.getCompanyId());
        companyProduct = companyProductService.insert(companyProduct);
        companyProduct.setQrcodeUrl(QRCode.rulesQRForSMPay(System.getProperty("catalina.base"), company.getUserId(), companyProduct.getProductId()));
        companyProductService.update(companyProduct);
        MsgOut o = MsgOut.success(company);
        return this.renderJson(o);
    }

//    /**
//     * 更新固定Id的商家
//     * @param company
//     * @return
//     */
//    @RequestMapping(value = "/api/companyUpdate")
//    public String updateUpdate(Company company) {
//        for(int i = 338;i <= 577;i++){
//            String companyName = this.getRandomCode();
//            company.setCompanyName(companyName);
//            Long l = new Long((long)i);
//            company.setCompanyId(l);
//            companyService.update(company);
//        }
//        MsgOut o = MsgOut.success("更新成功");
//        return this.renderJson(o);
//    }
//
//    /**
//     * 创建固定Id的商品
//     * @param goods
//     * @return
//     */
//    @RequestMapping(value = "/api/goodsCreate")
//    public String goodsCreate(Goods goods) {
//        for(int i = 0; i < 3; i++){
//            for(int j = 338; j <=577; j++){
//                Long l = new Long((long)j);
//                Long ll = new Long((long)5);
//                String goodsName = this.getRandomCode1();
//                goods.setGoodsName(goodsName);
//                goods.setGoodsProviderId(l);
//                goods.setCategoryId(ll);
//                goodsService.insert(goods);
//            }
//        }
//        MsgOut o = MsgOut.success("创建成功");
//        return this.renderJson(o);
//    }
//
//    /**
//     * 更新固定Id的商品
//     * @param goods
//     * @return
//     */
//    @RequestMapping(value = "/api/goodsUpdatre")
//    public String goodsUpdate(Goods goods) {
//        for(int i = 2712;i <= 3431;i++){
//            Long l = new Long((long)i);
//            String goodsName = this.getRandomCode1();
//            goods.setGoodsName(goodsName);
//            goods.setGoodsId(l);
//            goodsService.update(goods);
//        }
//        MsgOut o = MsgOut.success("创建成功");
//        return this.renderJson(o);
//    }
//
//    private String getRandomCode () {
//        String[] arry1 = {"北京","上海","广州","深圳","江苏","湖南","福州","江西","江南"};
//        String[] arry2 = {"e世界","百度","淘宝","京东","浪潮","网易","中关村","奥迪","宝马","奔弛","马自达","保时捷","西二旗"};
//        String[] arry3 = {"开发一部","开发二部","开发三部","开发四部","开发五部","开发六部","开发七部"};
//        StringBuilder result = new StringBuilder("");
//        int index1 = (int)Math.round(Math.random() * 8);
//        int index2 = (int)Math.round(Math.random() * 12);
//        int index3 = (int)Math.round(Math.random() * 6);
//        result.append(arry1[index1]);
//        result.append(arry2[index2]);
//        result.append(arry3[index3]);
//        return result.toString();
//    }
//
//    private String getRandomCode1 () {
//        String[] arry1 = {"进口","韩国","国产","法国","印度","美国"};
//        String[] arry2 = {"牛奶","饼干","美食","咖啡","狗粮","猫粮","香槟"};
//        String[] arry3 = {"  100g","  200g","  300g","  400g","  500g","  600g","  700g"};
//        StringBuilder result = new StringBuilder("");
//        int index1 = (int)Math.round(Math.random() * 5);
//        int index2 = (int)Math.round(Math.random() * 6);
//        int index3 = (int)Math.round(Math.random() * 6);
//        result.append(arry1[index1]);
//        result.append(arry2[index2]);
//        result.append(arry3[index3]);
//        return result.toString();
//    }

    /**
     * @api {delete} /api/company/{companyId} 后台管理-商家管理-商家删除
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/company/{companyId}
     * @apiPermission admin
     * @apiName updateCompany
     * @apiGroup Company
     * @apiParam {int} companyId 商户ID.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[{
     * "address": "北京市朝阳区四惠远洋商务1406",
     * "auditCause": "0",
     * "bankAccount": "0",
     * "bankDeposit": "0",
     * "bankId": "",
     * "bankName": "0",
     * "businessLicenseNumber": "",
     * "city": "",
     * "coPayType": 0,
     * "coType": 0,
     * "companyGoodsCategotyId": 0,
     * "companyId": 1,
     * "companyName": "龙蛙天乐",
     * "companyStatus": 1,
     * "companyType": 127,
     * "ctime": 1484202120549,
     * "district": "",
     * "districtId": 0,
     * "headimgurl": "http://www.ruitaowang.com/favicon.jpg",
     * "imgBusinessLicense": "",
     * "imgIdBack": "",
     * "imgIdFront": "",
     * "imgOrganizationCodeCertificate": "",
     * "imgTaxRegistrationCertificate": "",
     * "jmId": "130423199305264311",
     * "linkman": "王总",
     * "mobile": "18310882968",
     * "mtime": 1484202120549,
     * "pid": 0,
     * "province": "",
     * "rangeSort": 0,
     * "redirectType": 0,
     * "remark": "",
     * "rstatus": 0,
     * "userId": 0,
     * "xlErCert": ""
     * <p>
     * }]
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/company/{companyId}"
     * }
     */
    @RequestMapping(value = "/api/company/{companyId}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("companyId") Long companyId) {
        MsgOut o = MsgOut.success(companyService.delete(companyId));
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/company/{companyId} 后台管理-商家管理-商家详情ByPK
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/company/{companyId}
     * @apiPermission admin
     * @apiName findCompanyByPK
     * @apiGroup Company
     * @apiParam {int} companyId 商户ID.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":1
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/company/{companyId}"
     * }
     */
    @RequestMapping(value = "/api/company/{companyId}", method = RequestMethod.GET)
    public String findCompanyByPK(@PathVariable("companyId") Long companyId) {
        Company company = companyService.selectByPK(companyId);
        if (!ObjectUtils.isEmpty(company.getImgIdFront()) && !company.getImgIdFront().startsWith("http")) {
            company.setImgIdFront(base64ImgMapper.selectByPK(Long.valueOf(company.getImgIdFront())).getBase64());
        }
        if (!ObjectUtils.isEmpty(company.getImgIdBack()) && !company.getImgIdBack().startsWith("http")) {
            company.setImgIdBack(base64ImgMapper.selectByPK(Long.valueOf(company.getImgIdBack())).getBase64());
        }
        if (!ObjectUtils.isEmpty(company.getImgOrganizationCodeCertificate()) && !company.getImgOrganizationCodeCertificate().startsWith("http")) {
            company.setImgOrganizationCodeCertificate(base64ImgMapper.selectByPK(Long.valueOf(company.getImgOrganizationCodeCertificate())).getBase64());
        }
        if (!ObjectUtils.isEmpty(company.getXlErCert()) && !company.getXlErCert().startsWith("http")) {
            company.setXlErCert(base64ImgMapper.selectByPK(Long.valueOf(company.getXlErCert())).getBase64());
        }
        SysUser user = sysUserService.selectByPK(company.getUserId());
        //remark user info include headimgurl and nickname
        MsgOut o = MsgOut.success(company);
        o.setTitle(user.getNickname());
        o.setMsg(user.getHeadimgurl());
        o.setTotal(userOnlineService.count(companyId));
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/admin/companyInfo/index")
    public String getAdminCompanyInfo() {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Company company = companyService.selectByUserId(user.getId());
        if (!ObjectUtils.isEmpty(company)) {
            MsgOut o = MsgOut.success(company);
            return this.renderJson(o);
        } else {
            return this.renderJson(MsgOut.error("您还不是商家用户"));
        }
    }

    @RequestMapping(value = "/api/wap/yd/companyInfo")
    public String YDCompanyInfo() {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Company company = new Company();
        company.setCompanyType((byte) 10);
        company.setUserId(user.getId());
        List<Company> companys = companyService.select(company);
        if (!ObjectUtils.isEmpty(companys)) {
            MsgOut o = MsgOut.success(companys.get(0));
            return this.renderJson(o);
        } else {
            return this.renderJson(MsgOut.error("您还不是云动商家用户"));
        }
    }

    @RequestMapping(value = "/api/wap/companyInfo/{companyId}")
    public String findCompanyInfo(@PathVariable("companyId") Long companyId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        UserHistoricalTrace condition = new UserHistoricalTrace();
        condition.setUserId(user.getId());
        condition.setCompanyId(companyId);
        List<UserHistoricalTrace> userHistoricalTraces = userHistoricalTraceService.select(condition);
        //历史记录
        if (ObjectUtils.isEmpty(userHistoricalTraces)) {
            UserHistoricalTrace userHistoricalTrace = new UserHistoricalTrace();
            userHistoricalTrace.setCompanyId(companyId);
            userHistoricalTrace.setUserId(user.getId());
            userHistoricalTrace.setRemark(companyService.selectByPK(companyId).getHeadimgurl());
            userHistoricalTrace.setCompanyName(companyService.selectByPK(companyId).getCompanyName());
            userHistoricalTraceService.createUserHistoricalTrace(userHistoricalTrace);
        }
        //公司信息
        Company company = companyService.selectByPK(companyId);
        if (!ObjectUtils.isEmpty(company.getImgIdFront()) && !company.getImgIdFront().startsWith("http")) {
            company.setImgIdFront(base64ImgMapper.selectByPK(Long.valueOf(company.getImgIdFront())).getBase64());
        }
        if (!ObjectUtils.isEmpty(company.getImgIdBack()) && !company.getImgIdBack().startsWith("http")) {
            company.setImgIdBack(base64ImgMapper.selectByPK(Long.valueOf(company.getImgIdBack())).getBase64());
        }
        if (!ObjectUtils.isEmpty(company.getImgOrganizationCodeCertificate()) && !company.getImgOrganizationCodeCertificate().startsWith("http")) {
            company.setImgOrganizationCodeCertificate(base64ImgMapper.selectByPK(Long.valueOf(company.getImgOrganizationCodeCertificate())).getBase64());
        }
        if (!ObjectUtils.isEmpty(company.getXlErCert()) && !company.getXlErCert().startsWith("http")) {
            company.setXlErCert(base64ImgMapper.selectByPK(Long.valueOf(company.getXlErCert())).getBase64());
        }
        SysUser userout = sysUserService.selectByPK(company.getUserId());
        MsgOut o = MsgOut.success(company);
        o.setTitle(userout.getNickname());
        o.setMsg(userout.getHeadimgurl());
        o.setTotal(userOnlineService.count(companyId));
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/admin/companyInfo")
    public String adminCompanyInfo(Company company) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        company.setUserId(user.getId());
        List<Company> out = new ArrayList();
        List<Company> companies = companyService.select(company);
        if (!ObjectUtils.isEmpty(companies)) {
            for (Company where : companies) {
                out.add(where);
            }
            MsgOut o = MsgOut.success(out);
            return this.renderJson(o);
        } else {
            return this.renderJson(MsgOut.error("您还不是商家用户"));
        }
    }

    @RequestMapping(value = "/api/wap/companyInfo")
    public String wapCompanyInfo(Company company, @RequestHeader(value = "headId", required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser user = sysUserService.selectByPK(Long.parseLong(userId));
        company.setUserId(user.getId());
        List<Company> out = new ArrayList();
        List<Company> companies = companyService.select(company);
        if (!ObjectUtils.isEmpty(companies)) {
            for (Company where : companies) {
                out.add(where);
            }
            MsgOut o = MsgOut.success(out);
            return this.renderJson(o);
        } else {
            return this.renderJson(MsgOut.error("您还不是商家用户"));
        }
    }

    @RequestMapping(value = "/api/company/user/get")
    public String getUserCompany() {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Company company = new Company();
        company.setUserId(user.getId());
        List<Company> out = new ArrayList<>();
        List<Company> companies = companyService.select(company);
        for (Company where : companies) {
            if (where.getCompanyType() != 3 || where.getCompanyType() != 4) {
                out.add(where);
            }
        }
        if (!ObjectUtils.isEmpty(out)) {
            MsgOut o = MsgOut.success(out);
            return this.renderJson(o);
        } else {
            return this.renderJson(MsgOut.error("您还不是商家用户"));
        }
    }

    @RequestMapping(value = "/api/company/wallet/{companyId}")
    public String getCompanyWalletByCompanyId(@PathVariable("companyId") Long companyId) {

        WalletCompany walletCompany = walletCompanyService.selectByPK(companyId);
        if (ObjectUtils.isEmpty(walletCompany)) {
            walletCompany = new WalletCompany();
            walletCompany.setCompanyYestoday(0);
            walletCompany.setCompanyAmount(0);
            walletCompany.setCompanyId(companyId);
            walletCompany.setCompanyBalance(0);
            walletCompanyService.insert(walletCompany);
        }

        return this.renderJson(MsgOut.success(walletCompany));
    }

    @RequestMapping(value = "/api/company/wallet")
    public String getCompanyWallet(@RequestParam(defaultValue = "0") Integer is8, Long companyId) {//is8 1提现，0 商户中心
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Company company = companyService.selectByPK(companyId);
        if (ObjectUtils.isEmpty(company)) {
            return this.renderJson(MsgOut.error("您还不是商家用户"));
        }

        if (is8 == 1 && company.getCompanyType().intValue() == 8) {
            return this.renderJson(MsgOut.error("供货商禁止提现"));
        }

        WalletCompany walletCompany = walletCompanyService.selectByPK(company.getCompanyId());
        //今日收益 -> 余额
        if (ObjectUtils.isEmpty(walletCompany)) {
            walletCompany = new WalletCompany();
            walletCompany.setCompanyYestoday(0);
            walletCompany.setCompanyAmount(0);
            walletCompany.setCompanyId(company.getCompanyId());
            walletCompanyService.insert(walletCompany);
        }

        return this.renderJson(MsgOut.success(walletCompany));
    }

    @RequestMapping(value = "/api/wap/user/company/wallet/get")
    public String findUserCompanyWalletAll() {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        List out = new ArrayList();
        Company company = new Company();
        company.setCompanyId(user.getId());
        company.setCompanyType((byte) 0);
        company.setCompanyName("个人账户");
        Company companyTool = new Company();
        companyTool.setUserId(user.getId());
        List<Company> companys = companyService.select(companyTool);
        companys.add(company);
        return this.renderJson(MsgOut.success(companys));
    }

    /**
     * @api {get} /api/admin/company/wallet 后台管理-订单管理-公司钱包
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/company/wallet
     * @apiPermission admin
     * @apiName findWalletCompanyForPage
     * @apiGroup walletCompany
     * @apiParam {int} companyId 商户ID.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "companyAmount": 5800,
     * "companyBalance": 5800,
     * "companyId": 166,
     * "companyType": 1,
     * "companyYestoday": 0,
     * "ctime": 1500784179805,
     * "mtime": 1500784179805,
     * "remark": "五常市中梁国米有机水稻农民专业合作社",
     * "rstatus": 0
     * }
     * ]
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/admin/company/wallet"
     * }
     */
    @RequestMapping("/api/admin/company/wallet")
    public String findWalletCompanyForPage(WalletCompany walletCompany, int page) {
        walletCompany.setPage(page);
        if (!ObjectUtils.isEmpty(walletCompany.getSidx())) {
            walletCompany.setOrderBy(walletCompany.getSidx() + " " + walletCompany.getSord() + "," + walletCompany.getOrderBy());
        }
        List users = new ArrayList();
        List<WalletCompany> list = walletCompanyService.selectForPage(walletCompany);
        for (WalletCompany wc : list) {
            wc.setRemark(companyService.selectByPK(wc.getCompanyId()).getCompanyName());
            users.add(wc);
        }
        MsgOut o = MsgOut.success(users);
        o.setRecords(walletCompany.getRecords());
        o.setTotal(walletCompany.getTotal());
        return this.renderJson(o);
    }

    /**
     * 待审核
     *
     * @return
     */
    @RequestMapping(value = "/api/wap/company/coaudit")
    public String coAuditCompanies() {//城市合伙人  type 3，实体店面 0

        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        //3 只有城市合伙人 有 合伙人后台
//        Company coCityer = companyService.selectByUserId(user.getId());
//        if (ObjectUtils.isEmpty(coCityer) || coCityer.getCompanyType() != 3) {
//            return this.renderJson(MsgOut.error("你还不是城市合伙人."));
//        }

        //过滤 自己辖区的店铺 districtId
        District district = districtService.selectByCityUserId(user.getId());
        if (ObjectUtils.isEmpty(district)) {
            return this.renderJson(MsgOut.error("您还没有入驻，请联系工作人员。"));
        }

        Company where = new Company();
        where.setCompanyType((byte) 0);
        where.setCompanyStatus((byte) 0);
        where.setDistrictId(district.getId());
        List<Company> resList = companyService.select(where);

        MsgOut o = MsgOut.success(resList);
        return this.renderJson(o);
    }


    /**
     * 已审核
     *
     * @return
     */
    @RequestMapping(value = "/api/wap/company/coaudited")
    public String coAuditedCompanies() {//城市合伙人  type 3，实体店面 0

        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        //3 只有城市合伙人 有 合伙人后台
//        Company coCityer = companyService.selectByUserId(user.getId());
//        if (ObjectUtils.isEmpty(coCityer) || coCityer.getCompanyType() != 3) {
//            return this.renderJson(MsgOut.error("你还不是城市合伙人."));
//        }

        //过滤 自己辖区的店铺 districtId
        District district = districtService.selectByCityUserId(user.getId());
        if (ObjectUtils.isEmpty(district)) {
            return this.renderJson(MsgOut.error("您还没有入驻，请联系工作人员。"));
        }

        Company where = new Company();
        where.setCompanyType((byte) 0);
        where.setCompanyStatus((byte) 0);
        where.setDistrictId(district.getId());
        List<Company> resList = companyService.select(where);

        MsgOut o = MsgOut.success(resList);
        return this.renderJson(o);
    }

    /**
     * 城市合伙人 辖区店铺 审核操作
     *
     * @param company
     * @return
     */
    @RequestMapping(value = "/api/wap/company/auditing", method = RequestMethod.PUT)
    public String coAuditingCompanies(Company company) {//companyStatus 0, 1, 2

        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        //3 只有城市合伙人 有 合伙人后台
        Company coCityer = companyService.selectByUserId(user.getId());
        if (ObjectUtils.isEmpty(coCityer) || coCityer.getCompanyType() != 3) {
            return this.renderJson(MsgOut.error("你还不是城市合伙人."));
        }
        companyService.update(company);
        company = companyService.selectByPK(company.getCompanyId());
        if (company.getCompanyStatus() == 1 && company.getUserId() > 0) {
            //授权 grant
            roleService.grantUserRoleForAppend(company.getUserId(), "4");
        }
        return this.renderJson(MsgOut.success());
    }


    /**
     * @api {get} /api/admin/company/exPrice 后台管理-商家管理-商家列表-详情-运费
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/company/exPrice
     * @apiPermission admin
     * @apiName findCompanyExPrice
     * @apiGroup companyExPrice
     * @apiParam {int} companyId 商户ID.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "ctime":1498200960291,
     * "expriceId":36,
     * "heightBase":1,
     * "heightExtraPrice":0,
     * "logisticsName":"圆通",
     * "price":1200,
     * "provinceName":"甘肃"
     * }
     * ]
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/admin/company/exPrice"
     * }
     */
    @RequestMapping("/api/admin/company/exPrice")
    public String findCompanyExPrice(ExPrice exPrice, int page) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        List<ExPriceVO> citys = new ArrayList<>();
        exPrice.setPage(page);
        List<ExPrice> exPrices = exPriceService.selectForPage(exPrice);
        for (ExPrice exPrice1 : exPrices) {
            ExPriceVO exPriceVO = new ExPriceVO();
            exPriceVO.setProvinceName(districtService.selectByPK(Long.parseLong(exPrice1.getProvinceId())).getName());
            exPriceVO.setPrice(exPrice1.getPrice());
            exPriceVO.setExpriceId(exPrice1.getExpriceId());
            exPriceVO.setCtime(exPrice1.getCtime());
            exPriceVO.setLogisticsName(logisticsService.selectByPK(exPrice1.getLogisticsId()).getName());
            exPriceVO.setHeightBase(exPrice1.getHeightBase());
            exPriceVO.setHeightExtraPrice(exPrice1.getHeightExtraPrice());
            citys.add(exPriceVO);
        }
        MsgOut o = MsgOut.success(citys);
        o.setRecords(exPrice.getRecords());
        o.setTotal(exPrice.getTotal());
        return this.renderJson(o);
    }

    /**
     * @api {post} /api/admin/company/exPrice 后台管理-商家管理-运费管理
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/company/exPrice
     * @apiPermission admin
     * @apiName createCompanyExPrice
     * @apiGroup companyExPrice
     * @apiParam {int} companyId 商户ID.
     * @apiParam {int} logisticsId 快递公司ID.
     * @apiParam {int} price 首重价格.
     * @apiParam {string} provinceId 地区ID.
     * @apiParam {int} heightExtraPrice 续重价格.
     * @apiParam {int} heightBase 续重重量.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "companyId":70,
     * "ctime":1504594247520,
     * "expriceId":251,
     * "heightBase":1,
     * "heightExtraPrice":1100,
     * "logisticsId":7,
     * "mtime":1504594247520,
     * "price":11100,
     * "provinceId":"27"
     * }
     * ]
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/admin/company/exPrice"
     * }
     */
    @RequestMapping(value = "/api/admin/company/exPrice", method = RequestMethod.POST)
    public String createCompanyExPrice(ExPrice exPrice) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(exPrice.getCompanyId())) {
            return this.renderJson(MsgOut.error("请先注册"));
        }
        String[] stringArr = exPrice.getProvinceId().split(",");
        for (int i = 0; i < stringArr.length; i++) {
            District district = new District();
            district.setParentid(Long.parseLong(stringArr[i]));
            List<District> districts = districtService.select(district);
            for (District dtt : districts) {
                exPrice.setCityId(dtt.getId());
                exPrice.setProvinceId(stringArr[i]);
                exPriceService.insert(exPrice);
            }
        }
        MsgOut o = MsgOut.success(exPrice);
        return this.renderJson(o);
    }

    /**
     * @api {put} /api/admin/company/exPrice 后台管理-商家管理-商家列表-详情-运费修改
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/company/exPrice
     * @apiPermission admin
     * @apiName updateCompanyExPrice
     * @apiGroup companyExPrice
     * @apiParam {int} companyId 商户ID.
     * @apiParam {int} logisticsId 快递公司ID.
     * @apiParam {int} price 首重价格.
     * @apiParam {string} provinceId 地区ID.
     * @apiParam {int} heightExtraPrice 续重价格.
     * @apiParam {int} heightBase 续重重量.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "companyId":70,
     * "ctime":1504594247520,
     * "expriceId":251,
     * "heightBase":1,
     * "heightExtraPrice":1100,
     * "logisticsId":7,
     * "mtime":1504594247520,
     * "price":11100,
     * "provinceId":"27"
     * }
     * ]
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/admin/company/exPrice"
     * }
     */
    @RequestMapping(value = "/api/admin/company/exPrice", method = RequestMethod.PUT)
    public String updateCompanyExPrice(ExPrice exPrice) {
        if (ObjectUtils.isEmpty(exPrice.getProvinceId()) && ObjectUtils.isEmpty(exPrice.getLogisticsId())) {
            return this.renderJson(MsgOut.error("请输入更新条件"));
        }
        ExPrice ep = new ExPrice();
        ep.setLogisticsId(exPrice.getLogisticsId());
        if (!ObjectUtils.isEmpty(exPrice.getProvinceId())) {
            ep.setProvinceId(exPrice.getProvinceId());
        }
        List<ExPrice> exPrices = exPriceService.select(ep);
        for (ExPrice exPrice1 : exPrices) {
            exPrice1.setLogisticsId(exPrice.getLogisticsId());
            exPrice1.setPrice(exPrice.getPrice());
            exPriceService.update(exPrice1);
        }
        MsgOut o = MsgOut.success(exPrice);
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/admin/ws/company/exPrice 后台管理-微商管理-商家列表-详情-运费
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/ws/company/exPrice
     * @apiPermission admin
     * @apiName findCompanyExPriceWs
     * @apiGroup companyExPrice
     * @apiParam {int} companyId 商户ID.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "ctime":1498200960291,
     * "expriceId":36,
     * "heightBase":1,
     * "heightExtraPrice":0,
     * "logisticsName":"圆通",
     * "price":1200,
     * "provinceName":"甘肃"
     * }
     * ]
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/admin/ws/company/exPrice"
     * }
     */
    @RequestMapping("/api/admin/ws/company/exPrice")
    public String findCompanyExPriceWs(ExPrice exPrice, int page) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        List<ExPriceVO> citys = new ArrayList<>();
        exPrice.setPage(page);
        exPrice.setCompanyId(companyService.selectByUserId(user.getId()).getCompanyId());
        List<ExPrice> exPrices = exPriceService.selectForPage(exPrice);
        for (ExPrice exPrice1 : exPrices) {
            ExPriceVO exPriceVO = new ExPriceVO();
            exPriceVO.setProvinceName(districtService.selectByPK(Long.parseLong(exPrice1.getProvinceId())).getName());
            exPriceVO.setPrice(exPrice1.getPrice());
            exPriceVO.setExpriceId(exPrice1.getExpriceId());
            exPriceVO.setCtime(exPrice1.getCtime());
            exPriceVO.setHeightBase(exPrice1.getHeightBase());
            exPriceVO.setHeightExtraPrice(exPrice1.getHeightExtraPrice());
            citys.add(exPriceVO);
        }
        MsgOut o = MsgOut.success(citys);
        o.setRecords(exPrice.getRecords());
        o.setTotal(exPrice.getTotal());
        return this.renderJson(o);
    }

    /**
     * @api {post} /api/admin/ws/company/exPrice 后台管理-微商管理-运费管理
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/ws/company/exPrice
     * @apiPermission admin
     * @apiName createCompanyExPriceWs
     * @apiGroup companyExPrice
     * @apiParam {int} companyId 商户ID.
     * @apiParam {int} logisticsId 快递公司ID.
     * @apiParam {int} price 首重价格.
     * @apiParam {string} provinceId 地区ID.
     * @apiParam {int} heightExtraPrice 续重价格.
     * @apiParam {int} heightBase 续重重量.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "companyId":70,
     * "ctime":1504594247520,
     * "expriceId":251,
     * "heightBase":1,
     * "heightExtraPrice":1100,
     * "logisticsId":7,
     * "mtime":1504594247520,
     * "price":11100,
     * "provinceId":"27"
     * }
     * ]
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/admin/ws/company/exPrice"
     * }
     */
    @RequestMapping(value = "/api/admin/ws/company/exPrice", method = RequestMethod.POST)
    public String createCompanyExPriceWs(ExPrice exPrice) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(companyService.selectByUserId(user.getId()))) {
            return this.renderJson(MsgOut.error("请先注册商家"));
        }
        String[] stringArr = exPrice.getProvinceId().split(",");
        for (int i = 0; i < stringArr.length; i++) {
            exPrice.setCompanyId(companyService.selectByUserId(user.getId()).getCompanyId());
            exPrice.setProvinceId(stringArr[i]);
            exPriceService.insert(exPrice);
        }
        MsgOut o = MsgOut.success(exPrice);
        return this.renderJson(o);
    }

    /**
     * @api {put} /api/admin/company/exPrice 后台管理-商家管理-商家列表-详情-运费修改
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/company/exPrice
     * @apiPermission admin
     * @apiName updateCompanyExPriceWs
     * @apiGroup companyExPrice
     * @apiParam {int} companyId 商户ID.
     * @apiParam {int} logisticsId 快递公司ID.
     * @apiParam {int} price 首重价格.
     * @apiParam {string} provinceId 地区ID.
     * @apiParam {int} heightExtraPrice 续重价格.
     * @apiParam {int} heightBase 续重重量.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * "companyId":70,
     * "ctime":1504594247520,
     * "expriceId":251,
     * "heightBase":1,
     * "heightExtraPrice":1100,
     * "logisticsId":7,
     * "mtime":1504594247520,
     * "price":11100,
     * "provinceId":"27"
     * }
     * ]
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/admin/company/exPrice"
     * }
     */
    @RequestMapping(value = "/api/admin/ws/company/exPrice", method = RequestMethod.PUT)
    public String updateCompanyExPriceWs(ExPrice exPrice) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        ExPrice ep = new ExPrice();
        ep.setProvinceId(exPrice.getProvinceId());
        List<ExPrice> exPrices = exPriceService.select(ep);
        for (ExPrice exPrice1 : exPrices) {
            exPrice1.setPrice(exPrice.getPrice());
            exPrice1.setCompanyId(companyService.selectByUserId(user.getId()).getCompanyId());
            exPriceService.update(exPrice1);
        }
        MsgOut o = MsgOut.success(exPrices);
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/wap/company/goods3/all 公众号-共享通首页  店铺列表
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/company/goods3/all
     * @apiName all
     * @apiGroup Company
     * @apiParam {String} cityName 地区.
     * @apiParam {String} companyName 商家name.
     * @apiParam {Int} page 第几页.
     * @apiParam {Long} userId 用户Id（headId）.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     */
    @RequestMapping(value = "/api/wap/company/goods3/all", method = RequestMethod.GET)
    public String findCompanyGoods3All(String cityName, Company company, int page, @RequestHeader(value = "headId", required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(cityName)) {
            return this.renderJson(MsgOut.error("参数错误"));
        }
        District district = new District();
        if(cityName.contains("/")){
            String[] citys = cityName.split("/");
            String parentName = citys[0];
            cityName = citys[1];
            district.setName(parentName);
            List<District> districts = districtService.select(district);
            long id = districts.get(0).getId();
            district.setParentid(id);
        }
        List listOut = new ArrayList();
        district.setName(cityName);
        List<District> districts = districtService.select(district);
        Byte levelType = districts.get(0).getLevelType();
        //Long cityId = districts.get(0).getId();
        //String cityIds = String.valueOf(cityId);
        company.setPage(page);
        if(levelType == 1){
            company.setProvince(cityName);
        } else if(levelType == 2){
            company.setCity(cityName);
        }else{
            company.setDistrict(cityName);
        }
        List<CompanyVO> companies = companyService.findCompanyGoods(company);
        String sign = "no sign";
        for (CompanyVO c : companies) {
            if (company.getLongitude().equals("-1") && company.getLatitude().equals("-1")) {
                getGoods(c, listOut, 0 ,sign);
            } else if (c.getLongitude() != null && !c.getLongitude().equals("") ){
                double distance = c.getDistance();
                if(distance > 1000){
                    distance = distance / 1000;
                    distance = Double.parseDouble(String.format("%.1f", distance));
                    sign = "1kmup";
                } else {
                    sign = "1kmdown";
                }
//                double lon1 = Double.parseDouble(company.getLongitude());
//                double lat1 = Double.parseDouble(company.getLatitude());
//                double lon2 = Double.parseDouble(c.getLongitude());
//                double lat2 = Double.parseDouble(c.getLatitude());
//                double s = JwdUtils.GetDistance(lon1, lat1, lon2, lat2);
//                if(s > 1000){
//                    s = s / 1000;
//                    s = Double.parseDouble(String.format("%.1f", s));
//                    sign = "1kmup";
//                } else {
//                    sign = "1kmdown";
//                }
                getGoods(c, listOut, distance,sign);
            }
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(company.getRecords());
        o.setTotal(company.getTotal());
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/wap/company/nearBy 公众号-导航栏附近中获取5千米内的店铺列表，并根据距离排序
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/company/nearBy
     * @apiName nearBy
     * @apiGroup Company
     * @apiParam {Int} page 第几页.
     * @apiParam {Long} userId 用户Id（headId）.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     */
    @RequestMapping(value = "/api/wap/company/nearBy", method = RequestMethod.GET)
    public String findCompanyNearBy(Company company, int page, @RequestHeader(value = "headId", required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        List listOut = new ArrayList();
        company.setPage(page);
        List<CompanyVO> companies = companyService.findCompanyGoodsNearBy(company);
        String sign;
        for (CompanyVO c : companies) {
            double distance = c.getDistance();
            if(distance > 1000){
                distance = distance / 1000;
                distance = Double.parseDouble(String.format("%.1f", distance));
                sign = "1kmup";
            } else {
                sign = "1kmdown";
            }
            getGoods(c, listOut, distance, sign);
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(company.getRecords());
        o.setTotal(company.getTotal());
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/wap/searchCompany 公众号-首页搜索店铺
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/searchCompany
     * @apiName searchCompany
     * @apiGroup Company
     * @apiParam {String} companyName 商家信息(商家name).
     * @apiParam {Int} page 第几页.
     * @apiParam {Long} userId 用户Id（headId）.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     */
    @RequestMapping(value = "/api/wap/searchCompany", method = RequestMethod.GET)
    public String searchCompany(Company company,int page,@RequestHeader(value = "headId", required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        List listOut = new ArrayList();
        company.setPage(page);
        List<Company> companyList = companyService.searchCompany(company);
        for (Company c : companyList) {
            getGoods(c, listOut, 0, "no sign");
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(company.getRecords());
        o.setTotal(company.getTotal());
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/wap/searchCompanyByNear 公众号-本地搜索商品
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/searchCompanyByNear
     * @apiName searchCompanyByNear
     * @apiGroup Company
     * @apiParam {String} longitude  商家信息(经度).
     * @apiParam {String} latitude  商家信息(纬度).
     * @apiParam {String} searchName 搜索内容.
     * @apiParam {Int} page 第几页.
     * @apiParam {Long} userId 用户Id（headId）.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * <p>
     * {
     * "code":0,
     * "data":[
     * {
     * company:{
     * "address":"北京市朝阳区 远洋商务1406"
     * "collectionId": "",
     * "companyId": "281",
     * "companyIndustryId": "0",
     * "companyName": "梁品铺子",
     * "companyTypeId": "240",
     * "distance": "1",
     * "headimgurl": "http://static.ruitaowang.com/attached/file/2018/07/09/20180709155656054.jpg",
     * "latitude": "39.912360",
     * "longitude": "116.491300",
     * "slogan": 0,
     * "userId": 13,
     * }
     * coupons{
     * "companyId":"281"
     * "companyTypeId": "0",
     * "couponEndtime": "0",
     * "couponTime": "0",
     * "couponType": "0",
     * "ctime": "1539164331899",
     * "goodsId": "0",
     * "id": "6",
     * "mtime": "1539164331899",
     * "percentage": "0",
     * "price": 0,
     * "reach1": "100000",
     * "remark": ,
     * "rstatus": "",
     * "score1": "25000"
     * }
     * distance: "4.2",
     * goodsList: {
     * "categoryId": "10",
     * "ctime":"1510627244911"
     * "goodsDetail": "<p><img src="http://static.ruitaowang.com/attached/file/2017/11/14/20171114104212883.jpg" title="" alt="x1.jpg"/></p><p><img src="http://static.ruitaowang.com/attached/file/2017/11/14/20171114104221569.jpg" title="" alt="x2.jpg"/></p>",
     * "goodsDumySales": "531",
     * "goodsExPrice": "0",
     * "goodsId": "2495",
     * "goodsName": "nathome/北欧欧慕 红酒启瓶器 电动开瓶器 葡萄酒 酒具酒器",
     * "goodsOnline": "1",
     * "goodsPayType": "0",
     * "goodsProviderId": "281",
     * "goodsProviderType": "11",
     * "goodsRealPrice": "11300",
     * "goodsRecommendSort": "0",
     * "goodsScore": "0",
     * "goodsScreenPrice": "19900",
     * "goodsSn": "RT000000null",
     * "goodsStock": "0",
     * "goodsThum": "http://static.ruitaowang.com/attached/file/2017/11/14/20171114104239674.jpg",
     * "mtime": "1510627244911",
     * "rstatus": "0",
     * "selfSupport": "false"
     * }
     * "sign": "1kmup"
     * }
     * ],
     * "msg":"操作成功啦",
     * "title":"成功",
     * "type":"SUCCESS"
     * }
     * @apiError InternalServerError.
     * @apiErrorExample Error-Response:
     * HTTP/1.1 500 Internal Server Error
     * {
     * "timestamp":1504064947603,
     * "status":500,
     * "error":"Internal Server Error",
     * "exception":"java.lang.ArithmeticException",
     * "message":"/ by zero",
     * "path":"/api/wap/searchCompanyByNear"
     * }
     */
    @RequestMapping(value = "/api/wap/searchCompanyByNear", method = RequestMethod.GET)
    public String searchCompanyByNear(CompanyVO companyVO,String searchName, int page, @RequestHeader(value = "headId", required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        List listOut = new ArrayList();
        companyVO.setPage(page);
        companyVO.setGoodsName(searchName);
        List<Company> companyList = companyService.searchCompanyByNear(companyVO);
        String sign;
        for(Company c : companyList){
            if (c.getLongitude() != null && !c.getLongitude().equals("")) {
                double lon1 = Double.parseDouble(companyVO.getLongitude());
                double lat1 = Double.parseDouble(companyVO.getLatitude());
                double lon2 = Double.parseDouble(c.getLongitude());
                double lat2 = Double.parseDouble(c.getLatitude());
                double s = JwdUtils.GetDistance(lon1, lat1, lon2, lat2);
                if(s > 1000){
                    s = s / 1000;
                    s = Double.parseDouble(String.format("%.1f", s));
                    sign = "1kmup";
                } else {
                    sign = "1kmdown";
                }
                getGoodsForSearch(c, listOut, s, sign,searchName);
            }
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(companyVO.getRecords());
        o.setTotal(companyVO.getTotal());
        return this.renderJson(o);
    }

    /**
     * 根据店铺信息将商品，优惠券，距离，店铺是否距离当前位置1千米以内的标志放入map中，在将map放入listOut中。
     * @param c 店铺信息
     * @param listOut 输出集合
     * @param distance 距离
     * @param sign 是否距离当前位置1千米以内的标志
     */
    public void getGoods(Company c, List listOut, double distance ,String sign) {
        if (ObjectUtils.isEmpty(c.getHeadimgurl())) {
            c.setHeadimgurl("http://static.ruitaowang.com/attached/file/2018/07/18/20180718153138439.jpg");
        }
        HashMap map = new HashMap();
        map.put("company", c);
        map.put("distance", distance);
        map.put("sign",sign);
        Goods goods = new Goods();
        goods.setGoodsProviderId(c.getCompanyId());
        goods.setPage(1);
        goods.setRows(4);
        goods.setGoodsOnline((byte) 1);
        List<Goods> goodsList = goodsService.goodsForHomepage(goods);
        map.put("goodsList", goodsList);
        Coupon coupon = new Coupon();
        coupon.setCompanyId(c.getCompanyId());
        coupon.setCouponType((byte) 0);
        List<Coupon> coupons = couponService.select(coupon);
        if (!ObjectUtils.isEmpty(coupons)) {
            map.put("coupons", coupons);
        } else {
            map.put("coupons", "");
        }
        listOut.add(map);
    }

    /**
     * 与上个方法相比多了筛选搜索商品名字
     * @param c
     * @param listOut
     * @param s
     * @param sign
     * @param searchName
     */
    public void getGoodsForSearch(Company c, List listOut, double s ,String sign,String searchName) {
        if (ObjectUtils.isEmpty(c.getHeadimgurl())) {
            c.setHeadimgurl("http://static.ruitaowang.com/attached/file/2018/07/18/20180718153138439.jpg");
        }
        HashMap map = new HashMap();
        map.put("company", c);
        map.put("distance", s);
        map.put("sign",sign);
        Goods goods = new Goods();
        goods.setGoodsProviderId(c.getCompanyId());
        goods.setPage(1);
        goods.setRows(4);
        goods.setGoodsOnline((byte) 1);
        goods.setGoodsName(searchName);
        List<Goods> goodsList = goodsSearchService.select(goods);
        map.put("goodsList", goodsList);
        Coupon coupon = new Coupon();
        coupon.setCompanyId(c.getCompanyId());
        coupon.setCouponType((byte) 0);
        List<Coupon> coupons = couponService.select(coupon);
        if (!ObjectUtils.isEmpty(coupons)) {
            map.put("coupons", coupons);
        } else {
            map.put("coupons", "");
        }
        listOut.add(map);
    }

//    /**
//     * 移动端 区域代理商入住
//     *
//     * @param company
//     * @return
//     */
//    @RequestMapping(value = "/api/wap/company/regionalAgent", method = RequestMethod.POST)
//    public String createRegionalAgent(Company company) {
//        SysUser user = LYSecurityUtil.currentSysUser();
//        if (ObjectUtils.isEmpty(user)) {
//            return this.renderJson(MsgOut.error("Plz login."));
//        }
//        company.setUserId(user.getId());
//        companyService.insert(company);
//        MsgOut o = MsgOut.success(company);
//        return this.renderJson(o);
//    }

    /**
     * @api {get} /api/admin/company/count 公众号-店铺个数
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/company/count
     * @apiName count
     * @apiGroup Company
     * @apiParam {Long} companyId 商家Id.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     */
    @RequestMapping(value = "/api/admin/company/count", method = RequestMethod.GET)
    public String companyCount(Company company){
        Map map = new HashMap();
        long companyCount = companyService.count(company);
        map.put("companyCount",companyCount);
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/wap/interactiveForSearch 公众号-互动中搜索
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/interactiveForSearch
     * @apiName interactiveForSearch
     * @apiGroup Company
     * @apiParam {String} companyName 商家name.
     * @apiParam {Int} page 第几页.
     * @apiParam {Long} userId 用户Id（headId）.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     */
    @RequestMapping(value = "/api/wap/interactiveForSearch", method = RequestMethod.GET)
    public String interactiveForSearch(Company company,int page,int type, @RequestHeader(value = "headId", required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        company.setUserId(userId);
        company.setPage(page);
        List<CompanyVO> companyList;
        if(type == 1){
            companyList = companyService.selectForMyInteractive(company);
        } else {
            companyList = companyService.selectForInteractive(company);
        }

        List out=new ArrayList<>();
        if (!ObjectUtils.isEmpty(companyList)){
            for (CompanyVO c:companyList){
                if (ObjectUtils.isEmpty(companyService.selectByPK(c.getCompanyId()).getHeadimgurl())){
                    c.setRemark("http://static.ruitaowang.com/attached/file/2018/07/18/20180718153138439.jpg");
                } else {
                    c.setRemark(companyService.selectByPK(c.getCompanyId()).getHeadimgurl());
                }
                c.setCompanyName(companyService.selectByPK(c.getCompanyId()).getCompanyName());
                LsMsg lsMsg = new LsMsg();
                lsMsg.setPred((byte)6);//红包
                lsMsg.setCompanyId(c.getCompanyId());
                List<LsMsg> lsMsgList = lsMsgService.select(lsMsg);
                if (ObjectUtils.isEmpty(lsMsgList)) {
                    c.setIsRedEnvelopes(0); //没有红包
                } else {
                    for (LsMsg l : lsMsgList){
                        UserProfit userProfit = new UserProfit();
                        userProfit.setOrderId(l.getMsgId());
                        userProfit.setOrderType((byte)19);
                        Long count = userProfitService.count(userProfit);
                        count = count + 1;
                        if (l.getLuckyMoneyNum() > count){
                            c.setIsRedEnvelopes(1); //有红包
                            break;
                        } else {
                            c.setIsRedEnvelopes(0); //没有红包
                        }
                    }
                }
                c.setIsCoupon(0);   //没有优惠劵
                c.setIsReward(0);   //没有打赏
                //高级合伙人加上商家权限
//                if(c.getPayCommunity() != 1){
//                    QRCodeRecord qrCodeRecord = new QRCodeRecord();
//                    qrCodeRecord.setUserId(c.getUserId());
//                    List<QRCodeRecord> qrCodeRecordList = qrCodeRecordService.select(qrCodeRecord);
//                    if(qrCodeRecordList.get(0).getBuyStatus() == 2){
//                        c.setPayCommunity((byte)1);
//                    }
//                }
//                if(c.getUserId() == userId){
//                    c.setIsme(1);
//                } else {
//                    c.setIsme(0);
//                }
                out.add(c);
            }
        }
        MsgOut o = MsgOut.success(out);
        o.setRecords(company.getRecords());
        o.setTotal(company.getTotal());
        return this.renderJson(o);
    }
}
